package com.zsk.tool.ano;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import okhttp3.Request;

/**
 * 实现注解@RequestClient和@GetRequest注解功能
 *
 * @author keke
 * @date 2020/08/18
 */
public class MethodProxy implements InvocationHandler {

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> classz = method.getDeclaringClass();
        RequestClient requestClient = method.getDeclaringClass().getAnnotation(RequestClient.class);
        // 如果传进来的是一个接口 并且 @RequestClient存在则实现接口功能
        if (classz.isInterface() && requestClient != null) {
            return run(method, args);
        }
        throw new RuntimeException(classz.getName() + " must be a interface and annotation as @RequestClient");
        // return method.invoke(this, args);
    }

    /**
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    public Object run(Method method, Object[] args) throws Throwable {
        // 获取方法上的GetRequest注解
        GetRequest getRequest = method.getAnnotation(GetRequest.class);
        // 实现@Request注解功能
        if (getRequest != null) {
            return getRequest(getRequest, method, args);
        }
        // 实现getName方法
        if ("getName".equals(method.getName())) {
            return "$Proxy->" + method.getDeclaringClass().getName();
        }
        System.err.println(method.getName() + "() is override by return null");
        return null;
    }

    public Object getRequest(GetRequest getRequest, Method method, Object[] args) {
        String url = getRequest.url();
        Request request = new Request.Builder().url(url).get().build();
        try {
            return Http.HTTP.newCall(request).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
